package com.daisuxia.web.util;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class XmlUtil {

	private static final Logger log = LoggerFactory.getLogger(XmlUtil.class);
	/**
	 * 解析消息类型
	 */
	public static String optionMsgType(String msg){
		int startIndex = msg.indexOf("<MsgType><![CDATA[")+18;
		int endIndex = msg.indexOf("]]></MsgType>");
		String type = msg.substring(startIndex,endIndex);
		return type;
	}
	/**
	 * 解析EVENT消息内容
	 * @param objClass
	 * @param msg
	 * @return
	 */
	public static Object readMessage(Class objClass,String msg){
		try {
			JAXBContext jc = JAXBContext.newInstance(new Class[] {objClass});
			Unmarshaller u = jc.createUnmarshaller();
			Object ebean = objClass.cast(u.unmarshal(new StringReader(msg)));
			return ebean;
		} catch (JAXBException e) {
			e.printStackTrace();
			log.error("解析EVENT消息出错",e.getMessage());
		}
		return null;
	}


	/**
	 *
	 * @param clazz  xml绑定的对象的类
	 * @param object xml绑定的对象
	 * @return 解析后字符编码为UTF-8的xml字符串
	 * @throws Exception
	 */
	public static <T> String toXml(Class<T> clazz,Object object) throws Exception {
		 Map<String,JAXBContext> map = new ConcurrentHashMap<String, JAXBContext>();
		// 组装xml
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		Marshaller marshaller = null;
		JAXBContext context = null;
		String returnString = null;
		try{
			try {
				context = map.get(clazz.toString());
				if(context==null)
				{
					context = JAXBContext.newInstance(clazz);
					map.put(clazz.toString(), context);
				}
				marshaller = context.createMarshaller();
//				marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
				marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
				marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
				marshaller.marshal(object, os);
			} catch (Exception e) {
				log.error("组装消息报文错误：" + e.getMessage());
				throw e;
			}

			//转换为UTF-8的字符串
			if (os != null) {
				returnString = os.toString("UTF-8");
			}
		} finally{
			marshaller = null;
			if (os != null)
			{
				os.close();
			}
			os = null;
		}
		return returnString;

	}

}
